﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace 转发程序
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
           
            Startup += new StartupEventHandler(App_Startup);     
        }

        void App_Startup(object sender, StartupEventArgs e)
        {
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
        }


        /// <summary>
        /// 引起没有处理的异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            if (e.Exception.InnerException != null)
            {

                //写日志
                WriteLog("没有处理的异常:" + e.Exception.Message + "\r\n----------------------------------\r\n" + e.Exception.InnerException.ToString() + "\r\n" + e.Exception.InnerException.StackTrace + e.Exception.StackTrace);
            }
            else
            {
                //写日志
                WriteLog("没有处理的异常:" + e.Exception.Message + "\r\n----------------------------------\r\n" + e.Exception.ToString() + "\r\n" + e.Exception.StackTrace);

            }
            //这里用于处理异常
            //MessageBox.Show("没有处理的异常:" + e.Exception.Message + "\r\n----------------------------------\r\n" + e.Exception.InnerException.ToString() + "\r\n" + e.Exception.InnerException.StackTrace + e.Exception.StackTrace);
            //表示异常已经处理
            e.Handled = true;
            return;
        }


        /// <summary>
        /// 将错误信息写入文件
        /// </summary>
        public void WriteLog(string str)
        {
            string FileDirectory = AppDomain.CurrentDomain.BaseDirectory + "Log";

            //创建一个可以写文件的目录
            if (!System.IO.Directory.Exists(FileDirectory))
            {
                try
                {
                    System.IO.Directory.CreateDirectory(FileDirectory);
                }
                catch (UnauthorizedAccessException)
                {
                    MessageBox.Show("不能创建文件,请确定程序文件夹有可写权限\r\n如果文件夹只读可能会出现此问题\r\n您可以去掉文件夹只读属性后重试");
                    return;
                }
            }

            try
            {
                System.IO.File.AppendAllText(FileDirectory + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", str);
            }
            catch (Exception ex)
            {
                System.IO.File.WriteAllText(FileDirectory + "/" + Guid.NewGuid().ToString() + ".txt", "引发了写日志的异常:要写入的内容" + str + "," + ex.Message);
            }
        }
    }
}
